﻿using ComTools.Reflection;
using System;
using Unity;

namespace Ioc.Unity
{
    public class UnityCIContainer
    {
        private readonly IUnityContainer container;
        private static readonly UnityCIContainer instance = new UnityCIContainer();

        private static object _sync = new object();

        private UnityCIContainer()
        {
            //注入配置对象
            container = new UnityContainer();
            //注册依赖对象
            //container.RegisterType<ISysUserService, SysUserServiceImpl>();
            //container.RegisterType<ISysMenuService, SysMenuServiceImpl>();

            var registerDics = RegisterTypeManager.GetTypesList();
            string interfaceInfo = string.Empty;
            string implementInfo = string.Empty;
            foreach (var item in registerDics)
            {
                interfaceInfo = item.Value.Interface;
                implementInfo = item.Value.Implement;

                var interfaceInf = ReflectionHelper.GetType(interfaceInfo.Split(',')[0], interfaceInfo.Split(',')[1]);
                var implementInf = ReflectionHelper.GetType(implementInfo.Split(',')[0], implementInfo.Split(',')[1]);

                container.RegisterType(
                    ReflectionHelper.GetType(interfaceInfo.Split(',')[0], interfaceInfo.Split(',')[1]),
                    ReflectionHelper.GetType(implementInfo.Split(',')[0], implementInfo.Split(',')[1])
               );
            }

            //IUnityContainer moduleContainer = new UnityContainer();
            //IUnityContainer viewContainer = moduleContainer.CreateChildContainer();
            //moduleContainer.RegisterInstance<IUnityContainer>("SaleBus", viewContainer);
            //IUnityContainer test = moduleContainer.Resolve<IUnityContainer>("SaleBus");//此时会报错，因为父容器已经释放，所有子容器也将被释放。
            //接口注入
            //container.RegisterType<ApiLogic.IGroupPurchaseService, ApiLogic.GroupPurchaseServiceImpl>();
        }

        /// <summary>
        /// 单例
        /// </summary>
        public static UnityCIContainer Instance
        {
            get
            {
                if (instance == null)
                    lock (_sync)
                        if (instance == null)
                            return instance;

                return new UnityCIContainer();
            }
        }

        /// <summary>
        /// 获取注入容器
        /// </summary>
        public object GetService(Type serviceType)
        {
            return container.Resolve(serviceType);
        }
        /// <summary>
        /// 获取注入容器
        /// </summary>
        public T GetService<T>()
        {
            return container.Resolve<T>();
        }
    }
}
